import { h, ref } from 'vue';

import { Sort } from '@element-plus/icons-vue';
import {
  ElAutocomplete,
  ElDropdown,
  ElDropdownItem,
  ElDropdownMenu,
  ElIcon,
} from 'element-plus';

import { requestClient } from '#/api/request';

interface RenderOptions {
  filterData: Record<string, any>;
  sortData: Record<string, any>;
  url?: string;
  pickerDate?: [Date, Date];
  formData?: Record<string, any>;
  checkedGridClassIds?: any[];
  onFilterChange?: () => void;
  onSorterChange?: () => void;
  isSort?: boolean;
}

export function renderFilterHeader(params: any, options: RenderOptions) {
  const {
    filterData,
    sortData,
    url,
    pickerDate,
    formData,
    checkedGridClassIds,
    onFilterChange,
    onSorterChange,
    isSort = true,
  } = options;

  const suggestions = ref<any[]>([]);
  const noData = ref(false); // 新增无数据状态标记[2](@ref)

  const fetchSuggestions = async (queryStr: string) => {
    suggestions.value = []; // 重置建议列表
    noData.value = false; // 重置无数据状态

    if (!url) return;

    try {
      const { data } = await requestClient.post(url, {
        heardAutoCompleteName: params.column.property,
        keyword: queryStr,
        pickerDate,
        filterData,
        formData,
        checkedGridClassIds,
      });

      // console.warn('data', list);

      const results =
        data.list?.map((item: any) => ({
          value: `${item.value}`,
          label: item.label || `${item.value}`,
        })) || [];

      // 处理无数据情况[1,2](@ref)
      if (results.length === 0) {
        noData.value = true;
        suggestions.value = [
          {
            value: '',
            label: '无匹配数据',
            isNoDataItem: true, // 特殊标记
          },
        ];
      } else {
        suggestions.value = results;
      }
    } catch (error) {
      console.error('搜索失败:', error);
      noData.value = true;
      suggestions.value = [
        {
          value: '',
          label: '请求失败，请重试',
          isNoDataItem: true,
        },
      ];
    }
  };

  const handleSort = (value: string) => {
    Object.keys(sortData).forEach((key) => {
      // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
      if (key !== params.column.property) delete sortData[key];
    });

    if (value) {
      sortData[params.column.property] = value;
    } else {
      // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
      delete sortData[params.column.property];
    }

    onSorterChange?.();
    onFilterChange?.();
  };

  const renderSorter = () => {
    return h(
      ElDropdown,
      {
        class: 'sorter-dropdown',
        style: {
          marginTop: '4px',
          marginRight: '8px',
          float: 'right',
          cursor: 'pointer',
        },
      },
      {
        default: () => h(ElIcon, null, () => h(Sort)),
        dropdown: () =>
          h(ElDropdownMenu, null, () => [
            h(
              ElDropdownItem,
              { onClick: () => handleSort('asc') },
              () => '升序',
            ),
            h(
              ElDropdownItem,
              { onClick: () => handleSort('desc') },
              () => '降序',
            ),
            h(ElDropdownItem, { onClick: () => handleSort('') }, () => '重置'),
          ]),
      },
    );
  };

  const renderAutocomplete = () => {
    return h(
      ElAutocomplete,
      {
        modelValue: filterData[params.column.property] || '',
        'onUpdate:modelValue': (value: string) => {
          filterData[params.column.property] = value;
        },
        clearable: true,
        placeholder: '输入关键字搜索',
        filterable: true,
        popperClass: noData.value ? 'no-data-popper' : '', // 动态类名[2](@ref)
        fetchSuggestions: (query, cb) => {
          fetchSuggestions(query).then(() => cb(suggestions.value));
        },
        onSelect: (item: any) => {
          // 阻止无数据项被选中[1](@ref)
          if (!item.isNoDataItem) onFilterChange?.();
        },
        onClear: () => {
          // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
          delete filterData[params.column.property];
          onFilterChange?.();
        },
        onKeyup: (event: KeyboardEvent) => {
          if (event.key === 'Enter') onFilterChange?.();
        },
        size: 'small',
        style: { width: '100%' },
      },
      {
        // 自定义下拉项渲染[1](@ref)
        default: (scope: { item: any }) => {
          if (scope.item?.isNoDataItem) {
            return h(
              'div',
              {
                class: 'no-data-item',
                style: {
                  color: '#999',
                  textAlign: 'center',
                  cursor: 'default',
                },
              },
              scope.item.label,
            );
          }
          return h('div', null, scope.item?.label || '');
        },
      },
    );
  };

  return h('div', { class: 'filter-header' }, [
    h('div', { class: 'header-title' }, [
      h('span', { class: 'title-text' }, params.column.title),
      isSort && renderSorter(),
    ]),
    h(
      'div',
      {
        class: 'header-filter',
      },
      renderAutocomplete(),
    ),
  ]);
}
